<template>
  <el-dialog :visible.sync="dialogFormVisible" title="修改密码" :close-on-click-modal="false">
    <el-form ref="dataForm" label-position="left" label-width="90px" :model="dataForm"
             style='width: 400px; margin-left:50px;' :close-on-click-modal="false" :rules="rules" size="mini">
      <el-form-item label="密码" prop="password">
        <el-input v-model="dataForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="dataForm.checkPass" type="password"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
      <el-button size="mini" type="primary" @click="updatePassword">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { updatePwd } from '@/api/users'
  import{ resetDataForm } from '@/utils/tools'
  import { k } from '@/utils/tools'
  const Md5 = require('blueimp-md5')

  export default {
    name: 'editPasswordDialog',
    data(){
      return {
        dialogFormVisible: false,
        dataForm: {
          userId: null,
          password: null,
          checkPass: null
        },
        rules: {
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (this.dataForm.checkPass !== '') {
                  this.$refs.dataForm.validateField('checkPass')
                }
                callback()
              }, trigger: 'blur'
            }
          ],
          checkPass: [
            {required: true, message: '请再输入确认密码', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value !== this.dataForm.password) {
                  callback(new Error('两次输入密码不一致!'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      //打开新建用户
      handleCreate(id) {
        this.dataForm.userId = id
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          resetDataForm(this.$refs['dataForm'])
        })
      },
      updatePassword(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dataForm.password = Md5(this.dataForm.password, k(), false)
            updatePwd({userId: this.dataForm.userId, newPwd: this.dataForm.password}).then(res => {
              this.$emit('submited-password')
              this.dialogFormVisible = false
              this.$message({showClose: true, message: '修改成功', type: 'success'});
            })
          }
        })
      }
    }
  }
</script>
